package com.pdd.service.process.impl;

import com.pdd.commons.cdn.TCCloudUploadUtil;
import com.pdd.commons.enums.ResponseSuccessEnum;
import com.pdd.commons.response.ResponseEntity;
import com.pdd.commons.response.ResponseResult;
import com.pdd.commons.utils.FileMd5Util;
import com.pdd.commons.utils.OkHttpUtil;
import com.pdd.config.yml.CrawlerListConfig;
import com.pdd.config.yml.ImageConfig;
import com.pdd.model.dao.Gay_Pic_Content;
import com.pdd.model.vo.Image_Vo;
import com.pdd.service.Gay_Pic_ContentService;
import com.pdd.service.process.CrawlerProcess;
import net.coobird.thumbnailator.Thumbnails;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:liyangpeng
 * @date:2019/6/3 18:50
 */
@Component
public class DouTuBy52Process implements CrawlerProcess<Gay_Pic_Content> {

    private Logger logger= LoggerFactory.getLogger(DouTuBy52Process.class);

    @Autowired
    private Gay_Pic_ContentService gay_pic_contentService;

    @Autowired
    private CrawlerListConfig crawlerListConfig;

    @Autowired
    private ImageConfig imageConfig;

    @Autowired
    private TCCloudUploadUtil tcCloudUploadUtil;

    @Override
    public ResponseEntity startWork() {
        List<String> urls=crawlerListConfig.getDoutuby52();
        //总页数
        Integer totalPage=1;
        for (String url:urls) {
            for (int i = 1; i <= totalPage; i++) {
                String html=OkHttpUtil.get(url+i,   null,null,null);
                if(html==null){
                    continue;
                }
                Document baseDoc= Jsoup.parse(html);
                if(totalPage==1){
                    Elements page=baseDoc.select("select.page-select option");
                    totalPage=page.size();
                }
                List<Gay_Pic_Content> pic_contents=Analysis(baseDoc);
                for (Gay_Pic_Content pic_content:pic_contents) {
                    if(pic_content==null){
                        continue;
                    }
                    try{
                        gay_pic_contentService.addPicContent(pic_content);
                    }catch (Exception e){
                        continue;
                    }
                }
            }
        }
        return ResponseResult.RETURN_SUCCESS(ResponseSuccessEnum.CRAWLER_COLLECTION_SUCCESS);
    }

    @Override
    public List<Gay_Pic_Content> Analysis(Document baseDoc) {
        List<Gay_Pic_Content> pic_contents=new ArrayList<>();
        Elements post_list=baseDoc.select("div.img-blocks > div.img-block-item img");
        for (Element src: post_list) {
            String imgurl=src.absUrl("data-backup");
            Image_Vo image_vo=downloadImage(imgurl,imageConfig.savepath);
            //图片下载失败
            if(image_vo==null){
                continue;
            }
            Gay_Pic_Content gay_pic_content=new Gay_Pic_Content();
            BeanUtils.copyProperties(image_vo,gay_pic_content);
            gay_pic_content.setTitle(src.attr("alt").replace("表情图",""));
            gay_pic_content.setDescription(src.attr("alt").replace("表情图",""));
            //图片地址
            //水印图片地址
            gay_pic_content.setIsedit(0);
            gay_pic_content.setDefaultstr(gay_pic_content.getTitle());
            gay_pic_content.setStrnum(0);
            pic_contents.add(gay_pic_content);
            //图片属性
        }
        return pic_contents;
    }


    @Override
    public Image_Vo downloadImage(String url, String savePath) {
        try {
            Image_Vo image_vo=new Image_Vo();
            String endWith=url.substring(url.lastIndexOf(".")).toLowerCase();
            String downloadFileName= url.substring(url.lastIndexOf("/"),url.lastIndexOf("."))+endWith;
            String downloadFilePath=savePath+downloadFileName;
            String result=OkHttpUtil.downLoadImg(url,downloadFilePath);
            if(result.equals("success")){
                File image=new File(downloadFilePath);
                BufferedImage bufferedImage= ImageIO.read(image);
                image_vo.setImgwidth(bufferedImage.getWidth());
                image_vo.setImgheigth(bufferedImage.getHeight());
                image_vo.setImgsize(image.length());
                String imgmd5=FileMd5Util.getMd5Code(downloadFilePath);
                image_vo.setImgmd5(imgmd5);
                //原图上传
                String srcAccess=tcCloudUploadUtil.putObject(downloadFilePath,"1"+downloadFileName);
                //上传完毕删除图片
                image.delete();
                image_vo.setImgsrc(srcAccess);
                //水印加工上传
                String waterMarkFile=downloadFilePath.replace(endWith,"_wm"+endWith);
                boolean watemakePath=addWaterMark(image,image_vo.getImgwidth(),image_vo.getImgheigth(),waterMarkFile);
                //上传完毕删除图片
                File watemakefile=new File(waterMarkFile);
                watemakefile.delete();
                if(!watemakePath){
                    return null;
                }
                //水印图片名称
                String wmFileName= waterMarkFile.substring(waterMarkFile.lastIndexOf("/"));
                String wtmkAccess=tcCloudUploadUtil.putObject(waterMarkFile,"1"+wmFileName);
                image_vo.setWmkimgsrc(wtmkAccess);
                return image_vo;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("【表情包-爬虫】表情包图片下载失败:{}",url);
        }
        return null;
    }


    @Override
    public boolean addWaterMark(File file,Integer width,Integer heigth,String waterMarkFile) {
        InputStream inputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream("static/watermake.png");
        try {
            Thumbnails.of(file).size(width,heigth).watermark(ImageIO.read(inputStream),0.8f).outputQuality(0.8).toFile(waterMarkFile);
            return true;
        } catch (IOException e) {
            logger.info("【表情包-爬虫】表情包图片水印添加失败:{}",waterMarkFile);
        }
        return false;
    }
}
